package cz.acies.http;

import java.sql.Connection;
import java.util.Arrays;
import java.util.List;
import java.util.Properties;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import cz.acies.data.DBConnector;
import cz.acies.data.DBUpadaterAsbtract;

public class StartUpListener implements ServletContextListener
{
	
	public StartUpListener() {}
	
	@Override
	public void contextInitialized(ServletContextEvent event) {
		System.out.println("StartUpListener.contextInitialized()");
		ServletContext ctx = event.getServletContext();
		String jdbcUrl = (String) ctx.getInitParameter("jdbcUrl");
		String jdbcDriver = (String) ctx.getInitParameter("jdbcDriver");
		
		String data = (String) ctx.getInitParameter("jdbcParams");
		Properties props = parseProps(data);
		
		String dialectClass = (String) ctx.getInitParameter("uniqlDialect");
		
		DBConnector connector = DBConnector.instance();
		connector.setUrl(jdbcUrl);
		connector.setDriver(jdbcDriver);
		connector.setDialectClass(dialectClass);
		connector.setProps(props);
		connector.initialize();
		Connection conn = null;
		try {
			conn = connector.conn();
			//System.out.println("conn: " + conn);
			
			String updaterClass = (String) ctx.getInitParameter("updaterClass");
			System.out.println("updaterClass: " + updaterClass);
			Class<?> c = Class.forName(updaterClass);
			DBUpadaterAsbtract upadater = (DBUpadaterAsbtract) c.newInstance();
			upadater.setConnection(conn);
			upadater.setDBMetaData(connector.dbmd());
			upadater.setServletContext(ctx);
			upadater.execute();
			
		} catch (Exception exc) {
			exc.printStackTrace();
		} finally {
			if (conn != null) try { conn.close(); } catch (Exception exc) {}
		}
	}

	@Override
	public void contextDestroyed(ServletContextEvent event) {
		System.out.println("StartUpListener.contextDestroyed()");
	}

	// -----  -----------------------------------------------------------------
	
	private Properties parseProps(String data) {
		Properties result = new Properties();
		List<String> list = Arrays.asList(data.split("&"));
		for (String s : list) {
			String as[] = s.split("=");
			if (as.length == 2) {
				result.put(as[0], as[1]);
			} else if (as.length == 1) {
				result.put(as[0], "");
			}
		}
		return result;
	}

}
